package feed

import (
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	auth_user "go-papers/common/auth-user"
	"go-papers/models"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

func GetFeedBackList(c *gin.Context) {
	var data models.FeedBack
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	id := c.Request.FormValue("id")
	if id != "" {
		data.Id, _ = strconv.Atoi(id)
	}

	data.OpenId = c.Request.FormValue("openId")
	data.MemberId = tools.GetMemberId(c)
	data.ThirdUserId = auth_user.GetThirdUserId(c, data.OpenId)

	data.FeedType = c.Request.FormValue("feedType")
	data.MemberName = c.Request.FormValue("memberName")
	data.FeedStatus = c.Request.FormValue("feedStatus")
	data.FeedStart = c.Request.FormValue("feedStart")
	data.FeedEnd = c.Request.FormValue("feedEnd")

	result, count, err := data.GetPageSearch(pageSize, pageIndex)
	tools.HasError(err, "异常", -1)

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func GetFeedBack(c *gin.Context) {
	var data models.FeedBack
	data.OpenId = c.Request.FormValue("openId")
	data.MemberId = tools.GetMemberId(c)
	data.ThirdUserId = auth_user.GetThirdUserId(c, data.OpenId)
	data.Id, _ = tools.StringToInt(c.Param("id"))
	result, err := data.GetByGw()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func InsertFeedBack(c *gin.Context) {
	var data models.FeedBack

	err := c.ShouldBindBodyWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.OpenId = c.Request.FormValue("openId")
	data.MemberId = tools.GetMemberId(c)
	data.ThirdUserId = auth_user.GetThirdUserId(c, data.OpenId)

	if data.MemberId > 0 {
		var mm models.Member
		mInfo, _ := mm.GetByID(data.MemberId)
		if mInfo.MemberId != 0 {
			data.MemberName = mInfo.NickName
			data.MemberMomId = mInfo.MomUserId
			data.MemberMomName = mInfo.MomRealName
			data.MemberRegisterDay = mInfo.RegisterTime
			data.MemberAddr = mInfo.Province + " " + mInfo.City + " " + mInfo.Area + " " + mInfo.Address
			data.MemberPhone = mInfo.Phone
		}
	}

	data.FeedTime = time.Now().Format("2006-01-02 15:04:05")
	data.FeedStatus = "1"
	//data.CreatedAt = noeT
	//data.UpdatedAt = noeT
	result, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "数据插入失败："+err.Error(), nil)
		return
	}
	app.OK(c, result, "")
}

func DeleteFeedBack(c *gin.Context) {
	var data models.FeedBack

	IDS := tools.IdsStrToIdsIntGroup("id", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	app.OK(c, nil, msg.DeletedSuccess)
}
